﻿using System;
using System.Data;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

//Written by Malte Dan Baden Hansen
//Feel free to use any way you like, but please keep these credits :)

namespace BioBooking.WebClient
{
    public class ImageManipulator
    {
        public ImageManipulator()
        {
        }

        public Bitmap ResizeImage(Bitmap imageToResize, int width, int height)
        {
            Bitmap result = new Bitmap(width, height);

            using (Graphics graphics = Graphics.FromImage(result))
            {
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.High;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.DrawImage(imageToResize, 0, 0, result.Width, result.Height);
            }

            return result;
        }

        public enum ImageResizeMode
        {
            Both = 0,
            Width = 1,
            Height = 2
        }

        public Bitmap ResizeImage(string imagePath, int finalWidth, int finalHeight)
        {
            using (Bitmap bitmap = (Bitmap)Bitmap.FromFile(imagePath))
            {
                int width = 0;
                int height = 0;

                width = Math.Max(bitmap.Width, finalWidth);
                height = Math.Max(bitmap.Height, finalHeight);
                return ResizeImage(bitmap, width, height);
            }
        }

        public Bitmap ResizeImage(Bitmap image, int maxValue, ImageResizeMode mode)
        {
            float width = 0;
            float height = 0;

            if (mode == ImageResizeMode.Height)
            {
                float aspectRatio = (float)image.Width / (float)image.Height;
                height = maxValue;
                width = height * aspectRatio;
            }
            else if (mode == ImageResizeMode.Width)
            {
                float aspectRatio = (float)image.Height / (float)image.Width;
                width = maxValue;
                height = width * aspectRatio;
            }

            return ResizeImage(image, Convert.ToInt32(width), Convert.ToInt32(height));
        }

        public Bitmap ResizeImageByPercentage(Bitmap imageToResize, int percent)
        {
            int width = imageToResize.Width / 100 * percent;
            int height = imageToResize.Height / 100 * percent;

            return ResizeImage(imageToResize, width, height);
        }
    }
}